<template>
  <form-layout>
    <span slot="title">{{$t('login.signUp')}}</span>
    <v-form ref="signupForm" v-model="valid">
      <v-text-field
        :label="$t('login.username')"
        v-model.trim="signupForm.username"
        :rules="signupRules.username"
        :hint="$t('login.limitChar')"
        prepend-icon="account_box"
        required
      ></v-text-field>
      <v-text-field
        :label="$t('login.password')"
        v-model="signupForm.password"
        :rules="signupRules.password"
        :hint="$t('login.sixChars')"
        validate-on-blur
        prepend-icon="lock"
        :append-icon="showP1 ? 'visibility' : 'visibility_off'"
        :append-icon-cb="() => (this.showP1 = !showP1)"
        :type="showP1 ? 'text' : 'password'"
        required
      ></v-text-field>
      <v-text-field
        :label="$t('login.repeatPassword')"
        v-model.trim="signupForm.repeatPassword"
        :rules="signupRules.repeatPassword"
        validate-on-blur
        :hint="$t('login.sixChars')"
        prepend-icon="lock"
        :append-icon="showP2 ? 'visibility' : 'visibility_off'"
        :append-icon-cb="() => (this.showP2 = !showP2)"
        :type="showP2 ? 'text' : 'password'"
        required
      ></v-text-field>
      <v-text-field
        :label="$t('login.phone')"
        v-model.trim="signupForm.phone"
        :rules="signupRules.phone"
        prepend-icon="phone_iphone"
        validate-on-blur
        type="text"
        required
      ></v-text-field>
      <v-layout>
        <v-flex xs8 sm8 md8 lg8>
          <v-text-field
            :label="$t('login.code')"
            v-model="signupForm.code"
            :rules="signupRules.code"
            prepend-icon="security"
            type="text"
            required
          >
          </v-text-field>
        </v-flex>
        <v-flex xs4 sm4 md4 lg4>
          <v-btn v-if="allowSendCode" @click="handleSendCode">
            {{$t('login.sendCode')}}
          </v-btn>
          <v-btn v-else :disabled="!allowSendCode">
            <v-count :from="60" :to="0" @finish="allowSendCode = true"></v-count>s内有效
          </v-btn>
        </v-flex>
      </v-layout>

      <v-line>以下项目可选</v-line>

      <v-text-field
        :label="$t('login.email')"
        v-model="signupForm.email"
        :rules="signupRules.email"
        prepend-icon="email"
      ></v-text-field>
      <dynamic-tags-input
        :label="$t('login.interests')"
        :chips.sync="signupForm.interests"
        :hint="$t('starting.clickEditAdd')"
        prependIcon="label"
      ></dynamic-tags-input>
      <v-flex align-start class="d-inline-flex">
        <v-icon>face</v-icon>
        <span class="subheading ml-3">头像</span>
        <avatar-upload :avatar.sync="signupForm.avatar" class="d-inline-block"></avatar-upload>
      </v-flex>
      <v-btn @click="handleSignUp" block class="primary" :disabled="!valid">{{$t('login.signUp')}}</v-btn>
    </v-form>
  </form-layout>
</template>

<script>
  import VLine from '@/components/VLine'
  import FormLayout from '@/views/layout/FormLayout'
  import AvatarUpload from '@/components/AvatarUpload'
  import DynamicTagsInput from '@/components/DynamicTagsInput'
  import VCount from '@/components/VCount'
  import { validatePhone } from '@/utils/validate'
  import * as userApi from '@/api/user'

  export default {
    name: 'SignUp',
    components: { VLine, AvatarUpload, DynamicTagsInput, VCount, FormLayout },
    data: () => ({
      signupForm: {
        username: '',
        password: '',
        repeatPassword: '',
        phone: '',
        code: '',
        email: '',
        interests: [],
        avatar: ''
      },
      signupRules: {
        username: [
          v => !!v || '请填写用户名',
          v => (v.length >= 2 && v.length <= 20) || '用户名太短/太长'
        ],
        password: [
          v => !!v || '请填写密码',
          v => v.length >= 6 || '密码长度太短'
        ],
        repeatPassword: [
          v => !!v || '请再次输入密码',
          v => v.length >= 6 || '密码长度太短'
        ],
        phone: [
          v => !!v || '填写手机',
          v => validatePhone(v) || '手机号非法'
        ],
        code: [
          v => !!v || '请填写验证码',
          v => /^[0-9]{6}$/.test(v) || '非法验证码'
        ],
        email: []
      },
      valid: true,
      allowSendCode: true,
      showP1: false,
      showP2: false
    }),
    methods: {
      handleSignUp() {
        if (this.$refs.signupForm.validate()) {
          if (this.signupForm.password !== this.signupForm.repeatPassword) {
            return this.$notify.warning('两次密码输入不一致')
          }
          if (this.signupForm.email) {
            const validEmail = /^\w+([.-]?\w+)*@\w+([.-]?\w+)*(\.\w{2,3})+$/.test(this.signupForm.email)
            if (!validEmail) {
              return this.$notify.error('邮箱地址有误')
            }
          }
          userApi.createUser(this.signupForm).then(res => {
            switch (res.status) {
              case 200:
                this.$notify.success(`创建用户 ${this.signupForm.username} 成功`)
                this.$router.push({ path: 'login', query: { phone: res.data.phone }})
                break
              case 227:
                this.$notify.error(`验证码错误或已过期`)
                break
              case 233:
                this.$notify.error(`该手机号已被注册，请前往忘记密码找回`)
                this.allowSendCode = true
            }
          })
        }
      },
      handleSendCode() {
        if (!validatePhone(this.signupForm.phone)) {
          return this.$notify.error('无法发送验证码到非法手机号码')
        }
        if (this.signupForm.password !== this.signupForm.repeatPassword) {
          return this.$notify.warning('两次密码输入不一致')
        }
        userApi.sendCode(this.signupForm.phone).then(res => {
          if (res.status === 200) {
            this.allowSendCode = false
            this.$notify.success(`验证码已发送至${res.data.phone}`)
          } else {
            this.$notify.warning('60秒内不可重发哟')
          }
        })
      }
    }
  }
</script>
